package com.web.farme.application;

import com.web.farme.config.DefaultConfig;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.ArrayList;
import java.util.List;

public class DefaultContext implements ApplicationContextAware {


    private static ConfigurableEnvironment environment;

    private static ApplicationContext applicationContext;

    public static void setEnvironment(ConfigurableEnvironment environment) {
        DefaultContext.environment = environment;
    }

    public static ConfigurableEnvironment getEnvironment() {
        return DefaultContext.environment;
    }

    /**
     * 获取配置文件
     */
    public static <T extends DefaultConfig> T getConfig(Class<T> tClass) {
        T resutl;
        T t = null;
        try {
            t = tClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        Binder binder = Binder.get(environment);
        assert t != null;
        resutl = (binder.bind(t.getConfigKey(), Bindable.of(tClass)).get());
        return resutl;
    }


    /**
     * 获取配置文件列表
     *
     */
    public <T extends DefaultConfig> List<T> getConfigList(Class<T> tClass) {
        List<T> resultList;
        T t = null;
        try {
            t = tClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        Binder binder = Binder.get(environment);
        resultList = new ArrayList<>();
        assert t != null;
        resultList.add(binder.bind(t.getConfigKey(), Bindable.of(tClass)).get());
        return resultList;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        DefaultContext.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String beanName){
        return getApplicationContext().getBean(beanName);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}
